package com.treasure.hunt.main

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.*
import com.google.android.material.tabs.TabLayout
import com.module.lemlin.base.RecyclerViewHolder
import com.module.lemlin.base.loadCropImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.util.AnimManager
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.Category
import com.treasure.hunt.entity.Notice
import com.treasure.hunt.entity.Search
import com.treasure.hunt.goods.GoodsHomeFragment
import com.treasure.hunt.mode.GoodsViewMode
import com.youth.banner.adapter.BannerAdapter
import kotlinx.android.synthetic.main.fragment_main_home.*
import kotlinx.android.synthetic.main.item_goods_label.view.*


class MainHomeFragment : ViewModeFragment<GoodsViewMode>() {

    companion object {
        fun newInstance(): MainHomeFragment {
            return MainHomeFragment()
        }
    }

    private val searchAdapter =
        object : BannerAdapter<Search, RecyclerViewHolder>(
            mutableListOf(
                Search(id = 0, title = "输入关键字搜索")
            )
        ) {
            override fun onCreateHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
                val textView = TextView(parent.context)
                textView.layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                ).apply { }
                textView.gravity = Gravity.CENTER_VERTICAL
                textView.textSize = 13f
                textView.setTextColor(ColorUtils.getColor(R.color.FF_5B6783))
                return RecyclerViewHolder(textView)
            }

            override fun onBindView(
                holder: RecyclerViewHolder?, data: Search?, position: Int, size: Int
            ) {
                (holder?.itemView as? TextView)?.text = data?.title
            }
        }

    private val noticeAdapter =
        object : BannerAdapter<Notice, RecyclerViewHolder>(mutableListOf()) {
            override fun onCreateHolder(parent: ViewGroup?, viewType: Int): RecyclerViewHolder {
                val v: View =
                    LayoutInflater.from(parent!!.context)
                        .inflate(R.layout.item_home_notice, parent, false)
                return RecyclerViewHolder(v)
            }

            override fun onBindView(
                holder: RecyclerViewHolder?, data: Notice, position: Int, size: Int
            ) {
                val isHttps: Boolean = data.image.substring(0, 5).contains("http") ||
                        data.image.substring(0, 5).contains("https")
                holder?.itemView?.findViewById<TextView>(R.id.tvNoticeTitle)?.text = data?.title
                holder?.itemView?.findViewById<ImageView>(R.id.tvNoticeIcon)
                    ?.loadCropImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${data?.image}")
            }
        }

    override val layoutResId: Int
        get() = R.layout.fragment_main_home

    override fun viewModel(): GoodsViewMode {
        return createViewModel()
    }

    override fun initView() {
        BarUtils.addMarginTopEqualStatusBarHeight(llMainHomeBar)

        tlMainHomeLabelBody.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) = Unit

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabSelected(tab: TabLayout.Tab?) {
                vpMainHomeBody.currentItem = tab?.position ?: 0
            }
        })

        vpMainHomeBody.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) = Unit
            override fun onPageScrolled(
                position: Int, positionOffset: Float, positionOffsetPixels: Int
            ) = Unit

            override fun onPageSelected(position: Int) {
                tlMainHomeLabelBody.getTabAt(position)?.select()
            }
        })

        bvMainHomeSearch.setOnClickListener {
            MainSearchActivity.open(requireActivity())
        }
    }

    override fun initData() {
        viewModel.indexGetSearchWords()
        viewModel.indexGetNotice()
        viewModel.indexGetCategory()
    }

    override fun onRefreshLoad() {
        super.onRefreshLoad()
        viewModel.indexGetSearchWords()
        viewModel.indexGetNotice()
        viewModel.indexGetCategory()
    }

    override fun initViewMode() {
        viewModel.categoryLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS) {
                return@Observer
            }
            response.httpData?.data?.let {
                fillDateCategory(it)
            }
        })

        viewModel.noticeLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                if (bvMainHomeNotice.adapter == null)
                    bvMainHomeNotice//.addBannerLifecycleObserver(this)
                        .setUserInputEnabled(false)
                        .setAdapter(noticeAdapter.apply {
                            setDatas(it)
                        })
                else {
                    noticeAdapter.setDatas(it)
                }
            }
        })

        viewModel.searchLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                if (bvMainHomeSearch.adapter == null)
                    bvMainHomeSearch//.addBannerLifecycleObserver(this)
                        .setUserInputEnabled(false)
                        .setAdapter(searchAdapter.apply {
                            setDatas(it)
                        })
                else {
                    searchAdapter.setDatas(it)
                }
            }
        })
    }

    private fun fillDateCategory(category: MutableList<Category>) {

        tlMainHomeLabelBody.apply {
            removeAllTabs()
            for ((index: Int, item: Category) in category.withIndex()){
                addTab(newTab().apply {
                    val view: View = LayoutInflater.from(requireContext())
                        .inflate(R.layout.item_goods_label, null)
                    view.tvGoodsLabelName.text = item.name
                    val isHttps: Boolean = item.image.substring(0, 5).contains("http") ||
                            item.image.substring(0, 5).contains("https")
                    view.ivGoodsLabelIcon.loadCropImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${item.image}")
                    customView = view
                    tag = index
                })

            }
        }


        vpMainHomeBody.adapter = object : FragmentStatePagerAdapter(
            childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItem(position: Int): Fragment =
                GoodsHomeFragment.newInstance(category[position])

            override fun getCount(): Int = category.size

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {}
        }

        if (category.size > 0) {
            tlMainHomeLabelBody.getTabAt(0)?.select()
        }
    }

}